package com.di.base.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.di.base.dao.OrderTblDao;
import com.di.base.entity.OrderTbl;
import com.di.base.feign.AccountFeignClient;
import com.di.base.feign.StorageFeignClient;
import com.di.base.service.OrderTblService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.Double;
import java.util.Date;

/**
 * (OrderTbl)表服务实现类
 *
 * @author makejava
 * @since 2025-07-08 22:45:48
 */
@Slf4j
@Service
public class OrderTblServiceImpl extends ServiceImpl<OrderTblDao, OrderTbl> implements OrderTblService {

    @Resource
    private StorageFeignClient storageFeignClient;

    @Resource
    private AccountFeignClient accountFeignClient;

    @Override
    @GlobalTransactional(name = "create-order-tx", rollbackFor = Exception.class)
    public void createOrder(String userId, String productId, Integer count, Double price) {
        log.info("===> [订单创建开始] userId={}, productId={}, count={}, amount={}", userId, productId, count, price);
        Double amount = price * count;
        // 1. 调用库存服务，预扣库存
        log.info("===> 调用库存服务减少库存...");
        storageFeignClient.decrease(productId, count);
        log.info("===> 库存服务调用完成");

        // 2. 调用账户服务，预扣余额
        log.info("===> 调用账户服务扣减余额...");
        accountFeignClient.decrease(userId, amount);
        log.info("===> 账户服务调用完成");

        // 3. 订单本地逻辑，可写入数据库（此处模拟）
        log.info("===> 模拟订单数据保存成功");
        OrderTbl orderTbl = new OrderTbl();
        orderTbl.setUserId(userId);
        orderTbl.setProductId(productId);
        orderTbl.setCount(count);
        orderTbl.setAmount(amount);
        orderTbl.setXid(RootContext.getXID());
        orderTbl.setCreateTime(new Date());
        this.save(orderTbl);
        log.info("===> [订单创建成功] 全局事务即将提交");
    }
}

